<template>
  <el-card>
    <div slot="header">
      <el-row type="flex" justify="space-between">
        <h3>维护基本信息</h3>
        <!-- 按钮操作栏 -->
        <BtnRender :render="renderBtnsBar" />
      </el-row>
    </div>
    <div>
      <el-row>
        <GeneralRenderTable
          :loading="tableInfo.loading"
          :data-source="tableInfo.list"
          :columns="tableInfo.columns"
        />
      </el-row>
    </div>
  </el-card>
</template>
<script>
import GeneralRenderTable from '@/pages/commodity/modules/components/generalRenderTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { getAttributeTypeFn } from '@/pages/commodity/modules/utils';
import { isResponseSuccess } from '@/utils/bizUtils';
import { queryPerfectBasicInfoService, savePerfectBasicInfoService } from '@/api/commodity/commodityAccessManage/commodityToPerfect'
export default {
  components: {
    BtnRender,
    GeneralRenderTable
  },
  data () {
    return {
      tableInfo: {
        list: [],
        columns: [],
        loading: false
      },
      btnLoading: {
        submit: false
      },
      mainData: {},
      dynamicIdKey: 'dynamicCol' // 动态标识key
    }
  },
  mounted() {
    this.setBaiscInfo()
  },
  methods: {
    // jsx-render渲染按钮操作栏
    renderBtnsBar(h) {
      const basicBtns = [
        { label: '保存', method: this.handleSave, type: 'primary', loading: this.btnLoading.submit },
        { label: '返回', method: this.handleGoBack, type: 'default' }
      ]
      const btnList = basicBtns.map(item => ({ ...item, size: 'mini' }))
      return getBtnsBar(h, btnList);
    },
    // 返回
    handleGoBack() {
      this.$router.push({ name: 'commodityNotPerfection' })
    },
    // 保存
    async handleSave() {
      const data = this.getSubmitData()
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await savePerfectBasicInfoService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('保存成功')
        this.handleGoBack()
      }
    },
    // 获取基本信息
    async getBasicInfo() {
      const { productUuid } = this.$route?.query ?? {}
      const loadingFn = state => { this.tableInfo.loading = state }
      const res = await queryPerfectBasicInfoService(productUuid, loadingFn)
      return res
    },
    // 设基本信息数据
    async setBaiscInfo() {
      const res = await this.getBasicInfo()
      if (res?.retData) {
        const { main, attrList } = res.retData
        this.mainData = main ?? {}
        this.setTableColumns(attrList)
        this.setTableData(attrList)
      }
    },
    // 设置表格表列
    setTableColumns(attrList) {
      const baiscColumns = [
        { title: '品类', key: 'categoryPath' },
        { title: 'SPU编码', key: 'spuNo' },
        { title: '商品名称', key: 'productNameFinal' },
        { title: '品牌', key: 'brandName' }
      ]
      const dynamicColumns = attrList.map((item, index) => ({
        title: item.attrName,
        key: `${this.dynamicIdKey}${index}`,
        required: item.attrMust == '1',
        width: 160,
        type: getAttributeTypeFn(item.attrType)
      }))
      this.tableInfo.columns = [...baiscColumns, ...dynamicColumns]
    },
    // 设置表格数据
    setTableData(attrList) {
      const dynamicData = attrList.reduce((value, item, index) => {
        value[`${this.dynamicIdKey}${index}`] = {
          ...item,
          valueName: item.attrType == '04' ? (item.valueName ?? '').split(',').filter(item => item) : item.valueName,
          valueUuid: item.attrType == '04' ? (item.valueUuid ?? '').split(',').filter(item => item) : item.valueUuid,
        }
        return value
      }, { ...this.mainData })
      this.tableInfo.list = [dynamicData]
    },
    // 获取提交数据
    getSubmitData() {
      const { productUuid } = this.$route?.query ?? {}
      const notSpecList = []
      const dataSource = this.tableInfo.list[0]
      for (const key in dataSource) {
        if (key.indexOf(this.dynamicIdKey) != -1) {
          const spec = dataSource[key]
          notSpecList.push({
            attrInfo: spec.attrUuid || spec.attrName,
            officialFlag: spec.officialFlag,
            valueInfo: this.getSpecValueInfo(spec)
          })
        }
      }
      return { productUuid, notSpecList }
    },
    // 获取notSpecList的valueInfo属性值
    getSpecValueInfo(spec) {
      // 下拉单选/文本框
      if (['01', '05'].includes(spec.attrType)) return spec.valueName
      // 下拉多选框
      if (spec.attrType == '04') {
        const valueUuids = (spec.valueName ?? []).reduce((uuids, name) => {
          const valueItem = spec.allValueOptions.find(item => item.optionHtml == name)
          valueItem && uuids.push(valueItem.optionValue)
          return uuids
        }, [])
        return valueUuids.join(',')
      }
      // 下拉单选
      const opt = spec.allValueOptions.find(item => item.optionHtml == spec.valueName)
      return opt?.optionValue
    },
  }
}
</script>
